package com.tao.picture.base.data

import android.content.Context
import androidx.datastore.preferences.SharedPreferencesMigration
import androidx.datastore.preferences.core.edit
import androidx.datastore.preferences.core.stringPreferencesKey
import androidx.datastore.preferences.preferencesDataStore
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map

// 参考链接：https://developer.android.google.cn/topic/libraries/architecture/datastore?hl=zh_cn
const val PREFERENCE_NAME = "preference_girl"//定义 DataStore 的名字
val Context.dataStore by preferencesDataStore(PREFERENCE_NAME,
    produceMigrations = {
        // 迁移sp sharedPreferencesName文件名
        listOf(SharedPreferencesMigration(it, ""))
    })
// 定义key
val LAST_DATE = stringPreferencesKey(name = "date")

class PreferenceStore(val context: Context) {
    // 保存值
    suspend fun save(value: String) {
        context.dataStore.edit {
            it[LAST_DATE] = value
        }
    }

    suspend fun read(): String {
        // 取值
        return context.dataStore.data.map {
            it[LAST_DATE] ?: ""
        }.first()
    }
}